<?php
require_once 'lib/Cookie.php';
require_once 'lib/Service.php';

class UserService extends Service{

	public function __construct(){
		parent::__construct();
		$this->_datakey = $this->_config['redisDatabase']['user'];
	}

	/**
	 * 通过cookie得到用户
	 */
	public function getUserByCookie(){
		$cookie 	= new Cookie();
		$ck_value = $cookie->getCookie( $this->_config['cookie']['user_key'] );
		$pieces   = explode('|', $ck_value);
		if(empty($pieces)){
			return null;
		}

		$email    = rawurldecode($pieces[0]);
		$hash     = $pieces[1];
		$user_id   = $this->emailExists( $email );
		if( !$user_id ){
			return null;
		}

		$user = $this->getUserById($user_id);
		$hash2 = $cookie->authHash( $email, $user['password'], $this->_config['cookie']['hash_key'] );
		if($hash != $hash2){
			return null;
		}else{
			return $user;
		}

	}

	public function setUserCookie( $email, $password ){
		$cookie = new Cookie();
		$hash = $cookie->authHash( $email, $password, $this->_config['cookie']['hash_key']);
		/* 防止email有|符号，这里做两次encode, 用以防止账号伪造 */
		$ck_value = rawurlencode( rawurlencode($email)."|".$hash );
		//15d
		$cookie->setCookie( $this->_config['cookie']['user_key'], $ck_value, time()+1296000, $this->_config['cookie']['domain'],1);	
	}

	public function getUserById( $user_id ){

		$this->_redis->select( $this->_datakey );
		return $this->_redis->hGetAll( "user:".$user_id );

	}

	/**
	 * 激活账户
	 */
	public function activeUser( $domain, $nickname, $user_id ){
		$this->_redis->select( $this->_datakey );
		$options = array();
		$options['domain']   = $domain;
		$options['nickname'] = $nickname;
		$options['active_time']  = time();
		$options['status']  = 1;
		$ret = $this->_redis->set("user:domain:".$domain, $user_id);
		if($ret){
			$uret = $this->_redis->hMset( "user:".$user_id, $options );
			$ret = $uret;
		}else{
			$this->_redis->del("user:domain:".$domain);
		}

		return $ret;
	}

	public function doaminExists( $domain ){
		$this->_redis->select( $this->_datakey );
		if( $this->_redis->get( "user:domain:".$domain) )
			return true;
		else
			return false;
	}

	private function createEmail( $email, $user_id ){
		$this->_redis->select( $this->_datakey );
		$email = str_replace(":", "%3A", $email);
		return $this->_redis->set("user:email:".$email, $user_id);
	}

	public function createUser( $user_id, $options ){
		$this->_redis->select( $this->_datakey );
		$ret = 0;
		if(!empty($options)){
			$uret = $this->_redis->hMset("user:".$user_id, $options);
			if( $uret ){
				$eret = $this->createEmail($options['email'], $user_id);
				if(!$eret){
					$this->delTempUser($user_id);
				}
				$ret = $eret;
			}
		}
		return $ret;
	}

	private function delTempUser($user_id ){
		$this->_redis->select( $this->_datakey );
		$this->_redis->del("user:".$user_id);
	}

	public function emailExists($email){
		$this->_redis->select( $this->_datakey );
		$email = str_replace(":", "%3A", $email);
		$user_id = $this->_redis->get("user:email:".$email);
		return $user_id;
	}

}
